//
//  CDKRequestPort.m
//  ModelCreate
//
//  Created by tanxk_mini on 2018/11/19.
//  Copyright © 2018 runzezhihun. All rights reserved.
//

#import "CDKRequestPort.h"
#import "MDFModelCreate.h"

static NSString *obtionModelFile(NSString *fileName)  {  return [NSString stringWithFormat:@"CDK%@Model",[fileName capitalizedString]]; }

@interface CDKRequestPort ()

@property (nonatomic, strong) NSDictionary *jsonDict;

@end

@implementation CDKRequestPort

+ (CDKRequestPort *)shared {
    static id sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (NSString *)printPort:(NSString *)url{
    
    //请求swagger json数据
    self.jsonDict = [self requestJson:url];
    
    NSArray <NSDictionary *>*tags = self.jsonDict[@"tags"];
    __block NSMutableString *mString = [NSMutableString new];
    
    //保存所有的请求模型到port
    __block NSMutableString *requestModelNames = [NSMutableString new];
    __block NSMutableArray <NSString *> *classNames = [NSMutableArray new];
    
    [tags enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSString *name = obj[@"name"];
        NSString *description = obj[@"description"];
        
        NSDictionary *paths = self.jsonDict[@"paths"];
        NSDictionary *definitions = self.jsonDict[@"definitions"];
        
        NSString *header = [NSString stringWithFormat:@"\n%@%@\n",@"#pragma mark - ",description];
        [mString appendString:header];
        // 1. 创建文件夹
        NSString *filePath = [NSString stringWithFormat:@"%@/%@",self.hostPath,description];
        [[MDFModelCreate shared] createFolder:filePath];
        
        for (NSString *paths_key in paths)
        {
            NSDictionary *post = paths[paths_key][@"post"];
            NSString *paths_key_tags = post[@"tags"][0];
            
            if ([name isEqualToString:paths_key_tags])
            {
                //2. 生成port文件 定义所有接口的文件
                mString = [self createPortFile:mString paths_key:paths_key post:post];
                
                //3. 创建请求模型、Item模型
                [self createModelAndItemToPost:post definitions:definitions paths_key:paths_key filePath:filePath];
                
                //4. 收集所有请求模型类名
                NSString *portString = [paths_key componentsSeparatedByString:@"/"].lastObject;
                [requestModelNames appendString:obtionModelFile(portString)];
                [requestModelNames appendString:@"/"];
                
                //5. 收集所有请求模型类名
                [classNames addObject:obtionModelFile(portString)];
            }
        }
    }];
    [mString appendFormat:@"\n/**\n%@\n*/",requestModelNames];
    [[MDFModelCreate shared] setMethodsImportString:classNames];
//    NSLog(@"\n%@\n",mString);
    return mString;
}

/// 生成port文件 定义所有接口的文件
- (NSMutableString *)createPortFile:(NSMutableString *)mString paths_key:(NSString *)paths_key post:(NSDictionary *)post {
    
    //1.1 生成port文件 定义所有接口的文件

    __block NSMutableString *portString = [NSMutableString new];
    
    [[paths_key componentsSeparatedByString:@"/"] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [portString appendString:[obj capitalizedString]];
    }];
    
    //1.2 如果接口前缀是/则去掉  - (NSString *)substringFromIndex:(NSUInteger)from
    if ([paths_key hasPrefix:@"/"]) {
        paths_key = [paths_key substringFromIndex:1];
    }
    NSString *summary = post[@"summary"];
    NSArray  *parameters = post[@"parameters"];
    
    NSString *staticStr = [NSString stringWithFormat:@"\n%@\nstatic NSString *const K%@Address  = @\"%@\";\n",
                           [self obtionParameters:parameters summary:summary],
                           [portString capitalizedString],
                           paths_key];
    
    [mString appendFormat:@"\n%@%@",@"#pragma mark ",summary];
    [mString appendString:staticStr];
    
    return mString;
}

///创建请求模型、Item模型
- (void)createModelAndItemToPost:(NSDictionary *)post definitions:(NSDictionary *)definitions paths_key:(NSString *)paths_key filePath:(NSString *)filePath{
    
    //1. 创建文件夹 ///文件名为 /market/v1/banner/getIp 剔除‘/’ 并首字母大写 这么做的目的是为了接口重名
    __block NSMutableString *portString = [NSMutableString new];
    
    [[paths_key componentsSeparatedByString:@"/"] enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [portString appendString:[obj capitalizedString]];
    }];
    
    NSString *tempFilePath = [NSString stringWithFormat:@"%@/%@",filePath,portString];
    
    [[MDFModelCreate shared] createFolder:tempFilePath];
    
    //2. 创建请求模型
    //2.1 配置创建文件路径
    [[MDFModelCreate shared] setHostPath:[NSString stringWithFormat:@"%@/",tempFilePath]];
    
    //3. 创建Item模型 并写入成员变量
    NSString *ref = post[@"responses"][@"200"][@"schema"][@"$ref"];
    ref = [ref componentsSeparatedByString:@"/"].lastObject;
    
    if (definitions[ref])
    {
        NSMutableDictionary *properties = [NSMutableDictionary dictionary];
        for (NSString *definitions_key in definitions)
        {
            if ([definitions_key isEqualToString:ref])
            {
                NSDictionary *definitions_key_dict = definitions[definitions_key][@"properties"];
                
                for (NSString *properties_key in definitions_key_dict)
                {
                    NSDictionary *tempkeyDict = definitions_key_dict[properties_key];
                    properties[properties_key] = [NSString stringWithFormat:@"%@%@",tempkeyDict[@"description"],tempkeyDict[@"type"]];
                }
            }
        }
        [[MDFModelCreate shared] createItemFileH:portString dict:properties];
    }
    else
    {
        [[MDFModelCreate shared] createItemFileH:portString dict:nil];
    }
    //3.1 处理body请求参数问题
    NSDictionary *parameters = post[@"parameters"][0];
    
    if ([parameters[@"in"] isEqualToString:@"body"]) {
        NSString *ref = parameters[@"schema"][@"$ref"];
        NSString *bodyParamKey = [ref componentsSeparatedByString:@"/"].lastObject;
        NSDictionary *bodyParamKeyDict = definitions[bodyParamKey]; //obj[@"name"],obj[@"description"]
        NSMutableArray *array = [NSMutableArray array];
        [bodyParamKeyDict[@"properties"] enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, NSDictionary *obj, BOOL * _Nonnull stop) {
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            dict[@"name"] = key;
            dict[@"description"] = obj[@"description"];
            [array addObject:dict];
        }];
        [[MDFModelCreate shared] createModelFileM:portString array:array];
    } else {
        [[MDFModelCreate shared] createModelFileM:portString array:post[@"parameters"]];
    }
    [[MDFModelCreate shared] createModelFileH:portString];
    [[MDFModelCreate shared] createItemFileM:portString];
}
- (NSString *)obtionParameters:(NSArray *)parameters summary:(NSString *)summary{
    
    NSMutableString *mString = [NSMutableString string];
    
    //1. 标题
    if (parameters.count == 0) {
        [mString appendFormat:@"/// %@",summary];
        return mString;
    } else {
        [mString appendFormat:@"/// %@\n",summary];
    }
    [mString appendString:@"///\n"];
    //2. 请求参数
    [parameters enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (idx == parameters.count-1) {
            [mString appendFormat:@"/// %@ : %@ type:%@ style:%@",dict[@"name"],dict[@"description"],dict[@"type"],dict[@"in"]];
        } else {
            [mString appendFormat:@"/// %@ : %@ type:%@ style:%@\n",dict[@"name"],dict[@"description"],dict[@"type"],dict[@"in"]];
            [mString appendString:@"///\n"];
        }
    }];
    
    return mString;
}

- (NSDictionary *)requestJson:(NSString *)url {
    NSLog(@"开始请求");
    NSURL *url2 = [NSURL URLWithString:url];
    NSData *jsonData = [NSData dataWithContentsOfURL:url2];
    if (jsonData == nil) {
        NSLog(@"开始失败");
        return nil;
    }
    NSDictionary *appVersion = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    return appVersion;
}
@end
